<template>
    <div>
        <el-card v-show="show" shadow="always" :body-style="{ padding: '20px' }">
            <svg @click="toAddAds" t="1655264510296" class="icon" viewBox="0 0 1024 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="2149" width="32" height="32">
                <path
                    d="M512 958.016611c-119.648434 0-232.1288-46.367961-316.736783-130.559656-84.640667-84.255342-131.263217-196.255772-131.263217-315.455235 0-119.168499 46.624271-231.199892 131.232254-315.424271 84.607983-84.191695 197.088348-130.559656 316.736783-130.559656s232.1288 46.367961 316.704099 130.559656c84.67163 84.224378 131.263217 196.255772 131.263217 315.391587 0.032684 119.199462-46.591587 231.232576-131.263217 315.455235C744.1288 911.615966 631.648434 958.016611 512 958.016611zM512 129.983389c-102.623626 0-199.071738 39.743475-271.583282 111.936783-72.480581 72.12794-112.416718 168.063432-112.416718 270.079828s39.903454 197.951888 112.384034 270.047144c72.511544 72.191587 168.959656 111.936783 271.583282 111.936783 102.592662 0 199.071738-39.743475 271.583282-111.936783 72.480581-72.160624 112.416718-168.063432 112.384034-270.079828 0-102.016396-39.903454-197.919204-112.384034-270.016181C711.071738 169.759548 614.592662 129.983389 512 129.983389z"
                    p-id="2150" fill="#1296db"></path>
                <path
                    d="M736.00086 480.00086 544.00086 480.00086 544.00086 288.00086c0-17.664722-14.336138-32.00086-32.00086-32.00086s-32.00086 14.336138-32.00086 32.00086l0 192L288.00086 480.00086c-17.664722 0-32.00086 14.336138-32.00086 32.00086s14.336138 32.00086 32.00086 32.00086l192 0 0 192c0 17.695686 14.336138 32.00086 32.00086 32.00086s32.00086-14.303454 32.00086-32.00086L544.00258 544.00086l192 0c17.695686 0 32.00086-14.336138 32.00086-32.00086S753.696546 480.00086 736.00086 480.00086z"
                    p-id="2151" fill="#1296db"></path>
            </svg>
            <el-table ref="multipleTable" :data="docs" tooltip-effect="dark" style="width: 100%">
                <!-- @selection-change="handleSelectionChange" -->
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="name" label="广告名" width="120">
                </el-table-column>
                <el-table-column prop="type" label="广告类型" width="120">
                    <template slot-scope="{row,$index}">
                        <span v-show="row.type == 1">图片</span>
                        <span v-show="row.type == 0">文字</span>
                    </template>
                </el-table-column>
                <el-table-column label="有效" width="120">
                    <template slot-scope="{row,$index}">
                        <svg v-show="row.state" t="1655274652232" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="3146" width="16" height="16">
                            <path
                                d="M512 1024C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z m-114.176-310.954667a53.333333 53.333333 0 0 0 75.434667 0l323.328-323.328a53.333333 53.333333 0 1 0-75.434667-75.434666l-287.914667 283.306666-128.853333-128.853333a53.333333 53.333333 0 1 0-75.434667 75.434667l168.874667 168.874666z"
                                fill="#1afa29" p-id="3147"></path>
                        </svg>
                        <svg v-show="!row.state" t="1655274769525" class="icon" viewBox="0 0 1024 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="12617" width="16" height="16">
                            <path
                                d="M512 128C300.8 128 128 300.8 128 512s172.8 384 384 384 384-172.8 384-384S723.2 128 512 128zM768 576 256 576C217.6 576 192 550.4 192 512c0-38.4 25.6-64 64-64l512 0c38.4 0 64 25.6 64 64C832 550.4 806.4 576 768 576z"
                                p-id="12618" fill="#d81e06"></path>
                        </svg>
                    </template>
                </el-table-column>
                <el-table-column prop="comments" label="广告描述" width="120">
                </el-table-column>
                <el-table-column label="操作" show-overflow-tooltip>
                    <template slot-scope="{row,$index}">
                        <el-button @click="editImg(row)" icon="el-icon-edit-outline" circle size="mini"
                            style="background-color:#ecf5ff">
                        </el-button>
                        <el-button @click="deleteRow(row)" icon="el-icon-delete" circle size="mini"
                            style="background-color:#fef0f0">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- //分页器 -->
            <div style="display:table;margin:0 auto;margin-top:10px">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page.sync="pageInfo.current" :page-sizes="[5, 8, 10]" :page-size="pageInfo.pageSize"
                    layout="sizes, prev, pager, next" :total="pageInfo.totalItems"></el-pagination>
            </div>
            <!-- //对话框 -->
            <el-dialog :title="title" :visible.sync="dialogVisible" width="50%">
                <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="80px" :inline="false"
                    size="normal">
                    <el-form-item label="广告名" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item v-show="adsType == 1" label="广告类型">
                        <el-radio v-model="ruleForm.type" label="0">文字</el-radio>
                        <el-radio v-model="ruleForm.type" label="1">图片</el-radio>
                    </el-form-item>
                    <el-form-item label="有效">
                        <el-switch v-model="ruleForm.state" label="true"></el-switch>
                    </el-form-item>
                    <el-form-item label="备注" label-width="80px" prop="comments">
                        <el-input v-model="ruleForm.comments"></el-input>
                    </el-form-item>
                    <el-form-item label="轮播" v-show="ruleForm.type == 1">
                        <el-switch v-model="ruleForm.carousel" label="true"></el-switch>
                    </el-form-item>
                    <el-form-item label="高度" size="normal" v-show="ruleForm.type == 1">
                        <el-input placeholder="高度" v-model="ruleForm.height" oninput="value=value.replace(/[^0-9]/g,'')"
                            min="0" max="10" style="width:30%" type="number">
                            <template slot="append">px</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item v-if="ruleForm.type == 1" label="图片列表" size="normal">
                        <el-button @click="addImgs" size="mini" round>添加图片</el-button><br />
                        <!-- //图片插槽 -->
                        <li v-show="ruleForm.items !== []" v-for="(item, index) in ruleForm.items" :key="index"
                            @click="clearLi">
                            <span>x</span>
                            <div class="big">
                                <img src="item.sImg">
                                <div>
                                    <div>名称：{{ item.alt }}</div>
                                    <div>链接：{{ item.link }}</div>
                                </div>
                            </div>
                        </li>
                    </el-form-item>
                    <el-form-item v-else label="链接列表" size="normal">
                        <el-button @click="addLink" size="mini" round>添加链接</el-button><br />
                        <el-tag :key="index" v-for="(tag, index) in ruleForm.items" closable
                            :disable-transitions="false" @close="handleClose(tag)">
                            {{ tag.title }}
                        </el-tag>
                    </el-form-item>
                    <el-form-item>
                        <el-button v-if="adsType == 1" type="primary" @click="submitForm('ruleForm')">保存</el-button>
                        <el-button v-else type="primary" @click="submitForm('ruleForm')">保存</el-button>
                        <el-button @click="dialogVisible = false">返回</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <!-- //文字链接对话框 -->
            <el-dialog title="添加文本链接" :visible.sync="dialogVisibleLink" width="50%">
                <el-form :model="wordData" ref="ruleForm" :rules="wordDataRules" label-width="80px" :inline="false"
                    size="normal">
                    <el-form-item label="文字内容" prop="title">
                        <el-input v-model="wordData.title"></el-input>
                    </el-form-item>
                    <el-form-item label="链接" prop="link">
                        <el-input v-model="wordData.link"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitFormWord('ruleForm')">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <!-- //添加图片对话框 :before-close="handleClose"-->
            <el-dialog title="添加图片" :visible.sync="dialogVisible2" width="50%">
                <el-form :model="imgData" ref="imgData" :rules="imgDataRules" label-width="80px" :inline="false"
                    size="normal">
                    <el-form-item label="广告描述" prop="alt">
                        <el-input v-model="imgData.alt"></el-input>
                    </el-form-item>
                    <el-form-item label="链接" prop="link">
                        <el-input v-model="imgData.link"></el-input>
                    </el-form-item>
                    <el-form-item label="app链接">
                        <el-input v-model="imgData.appLink"></el-input>
                    </el-form-item>
                    <el-form-item label="app链接类型">
                        <el-select v-model="imgData.appLinkType" placeholder="请选择app链接类型">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- :on-preview="handlePictureCardPreview" :on-remove="handleRemove" -->
                    <el-form-item label="上传">
                        <el-upload class="avatar-uploader" action="http://127.0.0.1:8080/api/upload/files"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="imgData.sImg" :src="imgData.sImg" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item size="normal">
                        <el-button type="primary" @click="submitFormImg('ruleForm')">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { reqAdsList, reqDeleteRow, reqAddOneLink, reqAddOneAds, reqGetOne, reqUpdateOne, reqGetPage } from '@/api/ads'
export default {
    name: 'ads',
    data() {
        return {
            title: '',
            adsType: '',
            dialogVisibleLink: false,
            dialogVisible: false,
            dialogVisibleNew: false,
            dialogVisible2: false,
            show: true,
            docs: [],
            pageInfo: {
                current: 1,
                pageSize: 10,
                searchkey: "",
                total: 0,
            },
            options: [
                {
                    value: '0',
                    label: '文章'
                },
                {
                    value: '1',
                    label: '链接'
                }
            ],
            ruleForm: {
                carousel: true,
                comments: "",
                height: '',
                items: [],
                name: "",
                state: true,
                type: "1",
                radio: '1',
                title: '',
                id: ''
            },
            wordData: {
                alt: "",
                height: "",
                link: "",
                sImg: "",
                title: "",
                width: ""
            },
            imgData: {
                link: '',
                alt: "",
                appLink: '',
                appLinkType: "",
                sImg: '',
                height: "",
                title: "",
                width: ""
            },
            wordDataRules: {
                name: [
                    { required: true, message: '请输入 广告名', trigger: 'blur' }
                ],
                comments: [
                    { required: true, message: '请输入 备注', trigger: 'blur' },
                    { min: 5, max: 30, message: '5 到 30 位,只能包含字母、数字和下划线!', trigger: 'blur' },
                ]
            },
            imgDataRules: {
                alt: [
                    { required: true, message: '请输入 广告描述', trigger: 'blur' },
                ],
                link: [
                    { required: true, message: '请输入 鏈接', trigger: 'blur' },

                ],
            },
            rules: {
                name: [
                    { required: true, message: '请输入 广告名', trigger: 'blur' }
                ],
                comments: [
                    { required: true, message: '请输入 备注', trigger: 'blur' },
                    { min: 5, max: 30, message: '5 到 30 位,只能包含字母、数字和下划线!', trigger: 'blur' },
                ],
                link: [
                    { required: true, message: '请输入 备注', trigger: 'blur' },

                ],
                title: [
                    { required: true, message: '请输入 文字内容', trigger: 'blur' },
                ],
                alt: [
                    { required: true, message: '请输入 广告描述', trigger: 'blur' },
                ],

            }
        }
    },
    mounted() {
        //获取广告信息
        this.getAdsList()
    },
    methods: {
        //上传图片成功的钩子
        handleAvatarSuccess(res, file) {
            this.imgData.sImg = res.data.path;
        },
        //清楚图片
        clearLi() {
            this.ruleForm.items = []
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        //关闭链接标签
        handleClose(tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        },
        //获取广告信息
        async getAdsList() {
            let result = await reqAdsList()
            this.docs = result.data.docs
            this.pageInfo = result.data.pageInfo
        },
        //添加
        toAddAds() {
            this.ruleForm={}
            this.title = '添加广告信息'
            this.adsType = 1
            this.dialogVisible = true
        },
        //修改图片信息
        async editImg(row) {
            this.dialogVisible = true
            this.title = '修改图片信息'
            this.adsType = 2
            console.log(row);
            let result = await reqGetOne({ id: row.id })
            this.ruleForm.name = result.data.name
            this.ruleForm.state = result.data.state
            this.ruleForm.comments = result.data.comments
            this.ruleForm.height = result.data.height
            this.ruleForm.carousel = result.data.carousel
            this.ruleForm.id = result.data.id
            this.ruleForm.date = result.data.date
            this.ruleForm._id = result.data._id
            this.ruleForm.__v = result.data.__v
            this.imgData.date = result.data.date
            this.imgData._id = result.data._id
            this.imgData.__v = result.data.__v
            this.imgData.target = result.data.target
            this.imgData.appLink = result.data.appLink
            this.imgData.__v = result.data.__v
        },
        //总按钮，提交添加的廣告数据
        submitForm(formName) {
            // this.ruleForm.items.push(this.wordData)
            // this.ruleForm.items.push(this.imgData)
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    if (this.adsType = 1) {
                        const { carousel, comments, height, items, name, state, type } = this.ruleForm
                        let result = await reqAddOneAds({ carousel, comments, height, items, name, state, type })
                        if (result.status == 200) {
                            this.$message({ type: 'success', message: '添加成功' })
                            this.dialogVisible = false
                            //获取广告信息
                            this.getAdsList()
                        }

                    } else {
                        const { carousel, comments, height, id, name, state, type, _id, __v, items } = this.ruleForm
                        let result = await reqUpdateOne({ carousel, comments, height, id, name, state, type, _id, __v, items })
                        if (result.status == 200) {
                            this.$message({ type: 'success', message: '更新成功' })
                            this.dialogVisible = false
                            //获取广告信息
                            this.getAdsList()
                        }
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //添加图片
        addImgs() {
            this.dialogVisible = false
            this.dialogVisible2 = true
            this.dialogVisibleNew = false
        },
        //添加文字链接
        addLink() {
            this.dialogVisibleLink = true
            this.dialogVisible = false
        },
        //删除row
        async deleteRow(row) {
            await reqDeleteRow({ ids: row.id })
            //获取广告信息
            this.getAdsList()
        },
        //保存文字链接
        saveWordData() {
            this.dialogVisibleLink = false
            this.ruleForm.items.push(this.wordData)
            this.dialogVisible = true
            this.wordData = {}
        },
        //提交文字数据
        submitFormWord(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.dialogVisibleLink = false
                    this.ruleForm.items.push(this.wordData)
                    this.dialogVisible = true
                    this.wordData = {}
                    //获取广告信息
                    this.getAdsList()
                    // alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //提交圖片数据
        submitFormImg(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.dialogVisible2 = false
                    this.ruleForm.items.push(this.imgData)
                    this.dialogVisible = true
                    this.imgData = {}
                    //获取广告信息
                    this.getAdsList()
                    // alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //提交文字
        async saveUpdate() {
            this.dialogVisible = false
            const { carousel, comments, height, items, name, state, type } = this.ruleForm
            await reqAddOneLink({ carousel, comments, height, items, name, state, type })
            //获取广告信息
            this.getAdsList()
        },
        //分页
        async renderPageList(current = 1, pageSize = 10) {
            let searchkey = this.pageInfo ? this.pageInfo.searchkey : "";
            let state = this.pageInfo ? this.pageInfo.state : "";
            let user = this.pageInfo ? this.pageInfo.user : "";
            let targetCurrent = current;
            let result = await reqGetPage({
                current: targetCurrent,
                pageSize,
                searchkey
            });
            this.docs = result.data.docs
            //ComponentPaginationEnd
        },
        handleSizeChange(val) {
            console.log(val);
            console.log(`每页 ${val} 条`);
            let current = this.pageInfo ? this.pageInfo.current : 1;
            this.renderPageList(current, val);
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            let pageSize = this.pageInfo ? this.pageInfo.pageSize : 10;
            this.renderPageList(val, pageSize);
        }




    },
}
</script>   

<style lang="scss" scoped>
li {
    width: 100%;
    height: 100%;
    border: 1px solid #eee;
    border-radius: 5px;
    list-style: none;
    padding: 0;
    position: relative;

    span {
        position: absolute;
        left: 220px;
        top: -10px;

    }

    .big {
        display: flex;
        align-items: center;

        img {
            width: 70px;
            height: 70px;
        }
    }
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>